<!-- 年规 - 团队规划 - 部门 -->
<template>
  <view>
    <view class="pt-4 pb-25">
      <department-list :list="list" @change="onChange" />
      <view class="flex justify-center items-center py-4" @click="onAdd">
        <u-icon name="plus" color="#f4af22" size="32" />
        <view class="ml-2 text-28 c-primary">添加部门</view>
      </view>
    </view>
    <view class="bottom-wrap-16 px-3.75 bg-white" @click="onSubmit">
      <view class="btn-primary">保存</view>
    </view>
  </view>
</template>

<script setup>
import DepartmentList from '@/package_plan/components/department-list/department-list.vue'
import { getDepartmentList, postDepartmentAdd } from '@/common/http/module/plan'
import { useUserStore } from '@/store/user'
import { showToast } from '@/common/util/uni'
import { refreshPrePage } from '@/common/util/util'

const userStore = useUserStore()

const list = ref([])

function loadData() {
  getDepartmentList(userStore.currentSocietyId).then(res => {
    list.value = res.data || []
  })
}

function onChange(e) {
  console.log('onChange', e);
  list.value = e
}

function onAdd() {
  list.value = list.value.concat([{ name: '' }])
}

function onSubmit() {
  const emptyDepartments = list.value.filter(item => !item.name)
  if (emptyDepartments.length > 0) {
    showToast('请输入部门名称')
    return
  }

  const params = {
    club_id: userStore.currentSocietyId,
    department: list.value
  }
  postDepartmentAdd(params).then(() => {
    showToast('保存成功')
    refreshPrePage('refresh')
    setTimeout(() => {
      uni.navigateBack()
    }, 600);
  })
}

onLoad(() => loadData())
</script>
